package malus.shaofeng.com.beiwomusic;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Handler;
import android.os.Message;
import android.provider.Settings;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Toast;

import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.ViewUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;
import com.lidroid.xutils.view.annotation.ContentView;
import com.lidroid.xutils.view.annotation.ViewInject;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import malus.shaofeng.com.beiwomusic.fragment.MainHotRankFragment;
import malus.shaofeng.com.beiwomusic.fragment.MainMySpaceFragment;
import malus.shaofeng.com.beiwomusic.fragment.MainNewestArticleFragment;
import malus.shaofeng.com.beiwomusic.fragment.MainNightSpeakFragment;
import malus.shaofeng.com.beiwomusic.model.NewStory;

@ContentView(R.layout.activity_main)
public class MainActivity extends FragmentActivity  implements StoryDataInter {
    @ViewInject(R.id.main_view_pager)
    ViewPager viewPager;
    @ViewInject(R.id.home_rg_selector)
    RadioGroup homeSelect;
    @ViewInject(R.id.home_init_image)
    ImageView homeInitImage;
    List<Fragment> fragmentList;
    //上次点击回退的时间
    long lastTime;
    private ResponseInfo<Object> responseHotInfo;
    private ResponseInfo<Object> responseNewInfo;
    AlertDialog dialog;
    Handler handler=new Handler(){
        @Override
        public void handleMessage(Message msg) {
            int what = msg.what;
            switch (what){
                case 0:
                    //7秒后检查是否登录，如果没有则显示网络异常
                    if(!(homeInitImage.getVisibility()==View.GONE)){
                        //如果没有登录
                        dialog.show();
                    }
                    break;
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ViewUtils.inject(this);
        setInit();
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    Thread.sleep(7000);
                    handler.sendEmptyMessage(0);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }

    private void setInit(){
        dialog = new AlertDialog.Builder(this)
                .setTitle("网络异常")
                .setMessage("请您检查网络")
                .setPositiveButton("检查网络",new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        Intent wifiSettingsIntent = new Intent(Settings.ACTION_ACCESSIBILITY_SETTINGS);
                        startActivity(wifiSettingsIntent);
                    }
                })
                .setNegativeButton("退出程序",new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        finish();
                    }
                })
                .setCancelable(false)
                .create();

        //TODO 网络加载数据
        //TODO 传递数据到fragment
        //TODO 执行动画
        HttpUtils httpUtils = new HttpUtils();
        String path="http://kxai.cn/qms/ws/rank/hotList.json";
        httpUtils.send(HttpRequest.HttpMethod.POST, path, new RequestParams(),new RequestCallBack<Object>() {
            @Override
            public void onSuccess(ResponseInfo<Object> objectResponseInfo) {
                responseHotInfo=objectResponseInfo;

                HttpUtils httpUtils = new HttpUtils();
                String path="http://kxai.cn/qms/ws/rank/newList.json";
                httpUtils.send(HttpRequest.HttpMethod.POST, path, new RequestParams(),new RequestCallBack<Object>() {
                    @Override
                    public void onSuccess(ResponseInfo<Object> objectResponseInfo) {
                        responseNewInfo=objectResponseInfo;

                        setViewPager();
                        setLinkage();
                        setAnimation();
                    }

                    @Override
                    public void onFailure(HttpException e, String s) {
                    }
                });

            }

            @Override
            public void onFailure(HttpException e, String s) {
                Log.e("asd", "asdsa");
            }
        });
    }

    private void setAnimation() {
        Animation anim= AnimationUtils.loadAnimation(this, R.anim.popupwindow_fade_out);
        anim.setAnimationListener(new Animation.AnimationListener() {
            @Override
            public void onAnimationStart(Animation animation) {

            }

            @Override
            public void onAnimationEnd(Animation animation) {
                homeInitImage.setVisibility(View.GONE);
            }

            @Override
            public void onAnimationRepeat(Animation animation) {

            }
        });
        homeInitImage.startAnimation(anim);
    }

    /**
     * 设置联动
     */
    private void setLinkage(){
        homeSelect.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                switch (checkedId){
                    case R.id.home_select_btn_1:
                        viewPager.setCurrentItem(0);
                        break;
                    case R.id.home_select_btn_2:
                        viewPager.setCurrentItem(1);
                        break;
                    case R.id.home_select_btn_3:
                        viewPager.setCurrentItem(2);
                        break;
                    case R.id.home_select_btn_4:
                        viewPager.setCurrentItem(3);
                        break;
                }
            }
        });
        viewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                View childAt = homeSelect.getChildAt(position);
                switch (childAt.getId()){
                    case R.id.home_select_btn_1:
                        ((RadioButton)findViewById(R.id.home_select_btn_1)).setChecked(true);
                        break;
                    case R.id.home_select_btn_2:
                        ((RadioButton)findViewById(R.id.home_select_btn_2)).setChecked(true);
                        break;
                    case R.id.home_select_btn_3:
                        ((RadioButton)findViewById(R.id.home_select_btn_3)).setChecked(true);
                        break;
                    case R.id.home_select_btn_4:
                        ((RadioButton)findViewById(R.id.home_select_btn_4)).setChecked(true);
                        break;
                }
            }

            @Override
            public void onPageScrollStateChanged(int state) {
            }
        });
    }

    /**
     * 加载fragment
     */
    private void setViewPager() {
        fragmentList=new ArrayList<>();
        fragmentList.add(new MainHotRankFragment());
        fragmentList.add(new MainNewestArticleFragment());
        fragmentList.add(new MainNightSpeakFragment());
        fragmentList.add(new MainMySpaceFragment());
        viewPager.setAdapter(new FragmentPagerAdapter(getSupportFragmentManager()) {
            @Override
            public Fragment getItem(int position) {
                return fragmentList.get(position);
            }

            @Override
            public int getCount() {
                return fragmentList.size();
            }
        });
        viewPager.setCurrentItem(1);
    }

    @Override
    public ResponseInfo<Object> getHotData() {
        return responseHotInfo;
    }

    @Override
    public ResponseInfo<Object> getNewData() {
        return responseNewInfo;
    }

    @Override
    public void onBackPressed() {
        long currentTime=System.currentTimeMillis();
        if(currentTime-lastTime<2000){
            lastTime=currentTime;
            Toast.makeText(this,"双击退出程序",Toast.LENGTH_LONG).show();
        }else{
            super.onBackPressed();
        }

    }
}
